<?php
/**
 * Created by PhpStorm.
 * User: zhengmingwei
 * Date: 2020/11/8
 * Time: 12:33 下午
 */


namespace addons\uniprint\library;


use addons\uniprint\library\feie\HttpClient;
use app\admin\model\uniprint\Template;
use think\Exception;
use think\Log;

class printer
{

    protected static $configs = [];


    /**
     * 打印指定模板 指定设备
     * @param int $templateId 模板id
     * @param int $id 设备id
     * @param array $data 替换模板中变量的数组
     */
    public static function printing(int $templateId, int $id, array $data)
    {
        $template = Template::get($templateId);
        $printer = \app\admin\model\uniprint\Printer::get($id);

        if (empty(self::$configs)) {
            self::$configs = get_addon_config('uniprint');
        }

        $template = preg_replace_callback("/\{([a-zA-Z0-9_]+)\}/", function ($matches) use ($data) {
            if (isset($data[$matches[1]])) {
                return $data[$matches[1]];
            } else {
                return '';
            }
        }, $template->template);

        switch ($printer->brand_id) {
            case 'zhongwu':
                self::zhongwu($template, $printer);
                break;
            case 'yilianyun':
                self::yilianyun($template, $printer);
                break;
            case 'feie':
                self::feie($template, $printer);
                break;
        }
    }

    /**
     * 打印自定义模板
     * @param string $template 模板字符串
     * @param integer|null $id 如果不指定deviceId的话全部打印机都会打印
     */
    public static function printingTemplate(string $template, int $id = null)
    {
        $printerModel = new \app\admin\model\uniprint\Printer();
        if ($id) {
            $printers = $printerModel->where(['id' => $id])->select();
        } else {
            $printers = $printerModel->where(['enable' => 1])->select();
        }
        if (!empty($printers)) {

            if (empty(self::$configs)) {
                self::$configs = get_addon_config('uniprint');
            }

            /**
             * @var \app\admin\model\uniprint\Printer $printer
             */
            foreach ($printers as $printer) {
                $tmp = $template;
                switch ($printer->brand_id) {
                    case 'zhongwu':
                        if (is_array($template)) {
                            $tmp = $template['zhongwu'] ?? 'uniprint-中午';
                        }
                        try {
                            self::zhongwu($tmp, $printer);
                        } catch (\Exception $e) {
                            Log::record("中午打印机报错：" . $e->getMessage());
                        }
                        break;
                    case 'yilianyun':
                        if (is_array($template)) {
                            $tmp = $template['yilianyun'] ?? 'uniprint-易联云';
                        }
                        try {
                            self::yilianyun($tmp, $printer);
                        } catch (\Exception $e) {
                            Log::record("易联云打印机报错：" . $e->getMessage());
                        }
                        break;
                    case 'feie':
                        if (is_array($template)) {
                            $tmp = $template['feie'] ?? 'uniprint-飞鹅';
                        }
                        try {
                            self::feie($tmp, $printer);
                        } catch (\Exception $e) {
                            Log::record("飞鹅打印机报错：" . $e->getMessage());
                        }
                        break;
                }
            }
        }
    }

    /**
     * @param string $template
     * @param \app\admin\model\uniprint\Printer $printer
     * @throws \zhongwu\exceptions\BusinessException
     */
    public static function feie(string $template, \app\admin\model\uniprint\Printer $printer)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => self::$configs['feie']['USER'],
            'stime' => $time,
            'sig' => sha1(self::$configs['feie']['USER'] . self::$configs['feie']['UKEY'] . $time),
            'apiname' => 'Open_printMsg',
            'sn' => $printer->device_id,
            'content' => $template,
            'times' => $printer->number //打印次数
        );
        $client = new HttpClient(self::$configs['feie']['IP'], self::$configs['feie']['PORT']);
        if (!$client->post(self::$configs['feie']['PATH'], $msgInfo)) {
            throw new Exception('飞鹅云打印机sn：' . $printer->device_id . '打印失败');
        } else {
            //服务器返回的JSON字符串，建议要当做日志记录起来
            $result = $client->getContent();
        }
    }

    /**
     * @param string $template
     * @param \app\admin\model\uniprint\Printer $printer
     * @throws \zhongwu\exceptions\BusinessException
     */
    public static function zhongwu(string $template, \app\admin\model\uniprint\Printer $printer)
    {
        $rpc = new \zhongwu\protocol\RpcClient(self::$configs['zhongwu']['appid'], self::$configs['zhongwu']['appsecret'], 'http://api.zhongwuyun.com');
        $Zprinter = new \zhongwu\Printer($rpc);
        for ($i = 0; $i < $printer->number; $i++) {
            $res = $Zprinter->set_args($printer->device_id, $printer->device_secret)->cloud_print($template);
        }
    }

    /**
     * @param string $template
     * @param \app\admin\model\uniprint\Printer $printer
     * @throws \zhongwu\exceptions\BusinessException
     */
    public static function yilianyun(string $template, \app\admin\model\uniprint\Printer $printer)
    {
        $config = new \App\Config\YlyConfig(self::$configs['yilianyun']['appid'], self::$configs['yilianyun']['appsecret']);

        //获取token
        $uniprint = get_addon_config('uniprint');
        if (empty($uniprint['yilianyun']['access_token'])) {
            $client = new \App\Oauth\YlyOauthClient($config);
            $token = $client->getToken();   //若是开放型应用请传授权码code
            $uniprint['yilianyun']['access_token'] = $token->access_token;
            set_addon_config('uniprint', $uniprint);
        }
        // 在获取设备状态那里绑定设备

        //  调取文本打印;
        $print = new \App\Api\PrintService($uniprint['yilianyun']['access_token'], $config);
        for ($i = 0; $i < $printer->number; $i++) {
            $data = $print->index($printer->device_id, $template, time());
            //var_dump($data);exit;
        }
    }
}
